package student.aistar.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import student.aistar.model.entity.Product;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Auther: zhugefeng
 * @Date:2021/10/31 23:13
 **/
@RestController
public class ElasticsearchController {
    private RestHighLevelClient restHighLevelClient;

    public ElasticsearchController(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    @GetMapping("/search/tips")
    public Object autoComplete(String term) throws IOException {
        Request request = new Request("GET", "products/_search");
        request.setJsonEntity(String.format("{" +
                "  \"_source\": false," +
                "  \"suggest\": {" +
                "    \"product_tags_suggest\": {" +
                "      \"prefix\":\"%s\"," +
                "      \"completion\":{" +
                "        \"field\":\"tags.suggest\"," +
                "        \"size\":20," +
                "        \"skip_duplicates\":true" +
                "      }" +
                "    }" +
                "  }" +
                "}", term));
        Response response = restHighLevelClient.getLowLevelClient().performRequest(request);

        String jsonString = EntityUtils.toString(response.getEntity());

        JSONObject jsonObject = JSONObject.parseObject(jsonString);

        JSONArray suggests = jsonObject.getJSONObject("suggest").getJSONArray("product_tags_suggest");

        JSONArray options = suggests.getJSONObject(0).getJSONArray("options");

        List<String> results = new ArrayList<>();
        for (int i = 0; i < options.size(); i++) {
            JSONObject opt = options.getJSONObject(i);
            results.add(opt.getString("text"));
        }
        Request request2 = new Request("GET", "products/_search");
        request2.setJsonEntity(String.format("{" +
                "  \"_source\": false," +
                "  \"suggest\": {" +
                "    \"product_tags_suggest\": {" +
                "      \"prefix\":\"%s\"," +
                "      \"completion\":{" +
                "        \"field\":\"tags\"," +
                "        \"size\":20," +
                "        \"skip_duplicates\":true" +
                "      }" +
                "    }" +
                "  }" +
                "}", term));
        Response response2 = restHighLevelClient.getLowLevelClient().performRequest(request2);

        String jsonString2 = EntityUtils.toString(response2.getEntity());

        JSONObject jsonObject2 = JSONObject.parseObject(jsonString2);

        JSONArray suggests2 = jsonObject2.getJSONObject("suggest").getJSONArray("product_tags_suggest");

        JSONArray options2 = suggests2.getJSONObject(0).getJSONArray("options");

//        List<String> results = new ArrayList<>();
        for (int j = 0; j < options2.size(); j++) {
            JSONObject opt = options2.getJSONObject(j);
            results.add(opt.getString("text"));
        }
        return results;
    }

    @GetMapping("/search/so")
    public List<Product> query(String text) throws IOException {
        Request request = new Request("GET", "products/_search");
        request.setJsonEntity(String.format("{" +
                "  \"_source\": [\"product_id\",\"product_name\",\"price\",\"pic_img\",\"category_id\",\"introduce\",\"tags\"]," +
                "  \"query\": {" +
                "    \"multi_match\": {" +
                "      \"query\": \"%s\"," +
                "      \"fields\": [\"product_name\",\"introduce\",\"tags\"]" +
                "    }" +
                "  }" +
                "}", text));
        Response response = restHighLevelClient.getLowLevelClient().performRequest(request);

        JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));

        JSONArray hits = jsonObject.getJSONObject("hits").getJSONArray("hits");

        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < hits.size(); i++) {
            Product product = new Product();
            JSONObject hit = hits.getJSONObject(i);
            JSONObject sources = hit.getJSONObject("_source");
            product.setProductId(sources.getInteger("product_id"));
            product.setProductName(sources.getString("product_name"));
            product.setPrice(sources.getFloat("price"));
            product.setPicImg(sources.getString("pic_img"));
            product.setCategoryId(sources.getInteger("category_id"));
            product.setIntroduce(sources.getString("introduce"));
            product.setTags(sources.getString("tags"));

            productList.add(product);
        }

        return productList;
    }

}
